package com.wanmait.CarTrading.Util;


import java.sql.*;
import java.util.ResourceBundle;

public class DBHelper {
    private DBHelper(){}
    private static DBHelper dbHelper = new DBHelper();
    public static DBHelper getDBhelper(){
        return dbHelper;
    }
    private static String driver,url,user,password;
    static {
        ResourceBundle bundle = ResourceBundle.getBundle("dbconfig");
      driver=bundle.getString("driver");
      url=  bundle.getString("url");
      user=bundle.getString("user");
      password =bundle.getString("password");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public Connection getConn() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    public void update(String sql , Object ... objects)
    {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = this.getConn();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < objects.length; i++)
            {
                ps.setObject(i+1,objects[i]);
            }

            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.close(null,ps,conn);
        }
    }

    public void close(ResultSet rs, PreparedStatement ps, Connection conn)
    {

        if(rs!=null)
        {
            try
            {
                rs.close();
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
        if(ps!=null)
        {
            try
            {
                ps.close();
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
        if(conn!=null)
        {
            try
            {
                conn.close();
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
}


